<?php if (!defined('FIT_PATH')) exit('No direct script access allowed');
/**
 * @copyright 2009 - 2011 Bincent.com. All Rights Reserved.
 * @license http://www.apache.org/licenses/LICENSE-2.0
 * @package	FitPHP
 * @subpackage library
 * 
 * @author Hongbin Hsu <hongbin.hsu@gmail.com> Initial.
 * @version $Id: library/thumb.php 1.0 2010-09-18 16:52 hongbin.hsu $
 */
 
// ------------------------------------------------------------------------

class Library_Thumb
{
	private $file_name;
	private $src_width;
	private $src_height;
	private $dst_width;
	private $dst_height;
	private $image_type;
	
	//----------------------------------------------------------
	/**
	 * 构造函数
	 *
	 * @param string $file_name
	 */
	public function __construct($file_name){
		try {
			if (is_file($file_name)) {
				$this->file_name = $file_name;
			}else{
				throw new Exception('Not find file');
			}
		}catch (Exception $e){
			echo $e->getMessage();
		}
	}
	
	//----------------------------------------------------------
	/**
	 * 设置缩略图的大小
	 *
	 * @param int $width
	 * @param int $height
	 */
	public function set_resize($width, $height){
		$this->dst_width = $width;
		$this->dst_height = $height;
	}
	
	//----------------------------------------------------------
	/**
	 * 创建缩略图
	 *
	 * @return string
	 */
	public function create(){
		$this->set_image_size();
		$srcImage = $this->create_from();
		$dstImage = imagecreatetruecolor($this->dst_width, $this->dst_height);
		imagecopyresized($dstImage,$srcImage,0,0,0,0,$this->dst_width,
					$this->dst_height,$this->src_width,$this->src_height);
		imagejpeg($dstImage,$file_name);
		return $file_name;
	}
	
	//----------------------------------------------------------
	/**
	 * 读取文件并创建图像对象
	 *
	 * @param int $type
	 * @param string $file_name
	 */
	private function create_from(){
		try {
			switch ($this->image_type){
				case 1:
					$srcImage = imagecreatefromgif($this->file_name);
				break;
				case 2:
					$srcImage = imagecreatefromjpeg($this->file_name);
				break;
				case 3:
					$srcImage = imagecreatefrompng($this->file_name);
				default:
					throw new Exception('Can not create format');
				break;
			}
			return $srcImage;
		}catch (Exception $e){
			echo $e->getMessage();
		}
	}
	
	//----------------------------------------------------------
	/**
	 * 设置图像大小
	 *
	 * @return void
	 */
	private function set_image_size(){
		$imageInfo = getimagesize($this->file_name);
		$this->src_width = $imageInfo[0];
		$this->src_height = $imageInfo[1];
		$this->image_type = $imageInfo[2];
	}
}